package com.azirkxs.clothes.cys.service.impl;

import com.azirkxs.clothes.cys.entity.Armoire;
import com.azirkxs.clothes.cys.mapper.ArmoireMapper;
import com.azirkxs.clothes.cys.service.IArmoireService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author azirkxs
 * @since 2023-04-09
 */
@Service
public class ArmoireServiceImpl extends ServiceImpl<ArmoireMapper, Armoire> implements IArmoireService {

    @Override
    public Map<String,Object> getArmoireTagsByArmoireId(Integer armoire_id) {
        Map<String,Object> data = new HashMap<>();
        List<Map> clothesList = this.baseMapper.getArmoireTagsByArmoireId(armoire_id);
        data.put("clothesId",clothesList);
        return data;
    }

    @Override
    public void updateArmoire(Integer id, String name, List<Integer> tagIds) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("armoireId", id);
        paramMap.put("name", name);
        this.baseMapper.updateArmoireName(paramMap);
        this.baseMapper.deleteArmoireTags(id);

        if (tagIds != null && !tagIds.isEmpty()) {
            paramMap.put("armoireId", id);
            paramMap.put("tags", tagIds);
            this.baseMapper.insertArmoireTags(paramMap);
        }
    }

    @Override
    public void createArmoire(String name, List<Integer> tagIds,Integer userId) {
        Armoire armoire = new Armoire();
        armoire.setName(name);

        // 插入衣柜名称，返回插入的记录数
        int affectedRows = this.baseMapper.createArmoire(armoire);
        if (affectedRows > 0) {
            // 获取插入的衣柜ID
            Integer armoireId = armoire.getArmoireId();
            // 插入用户和衣柜表
            Map<String,Object> data = new HashMap<>();
            data.put("userId",userId);
            data.put("armoireId",armoireId);
            this.baseMapper.addArmoireToUser(data);
            if (tagIds != null && !tagIds.isEmpty()) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("armoireId", armoireId);
                paramMap.put("tags", tagIds);

                // 在 armoire_tags 表中插入标签
                this.baseMapper.insertArmoireTags(paramMap);
            }
        }
    }

    @Override
    public void deleteArmoire(Integer id) {
        // 先删除 armoire_tags 中的对应数据
        this.baseMapper.deleteArmoireTags(id);

        // 再删除 armoire 表中的对应数据
        this.baseMapper.deleteArmoire(id);

        this.baseMapper.deleteArmoireFromUser(id);
    }
}
